//
//  MyAssetInfoVC.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/2/6.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "MyAssetInfoVC.h"
#import "AppHeader.h"

#import "AssetHeaderView.h"
#import "AssetInfoCell.h"
#import "RechargeListView.h"
#import "PayTypeAlertView.h"

#import "MineRecordsModel.h"
#import "UserAccountModel.h"


#import <AlipaySDK/AlipaySDK.h>

#import "APOrderInfo.h"



@interface MyAssetInfoVC () <UITableViewDelegate, UITableViewDataSource> {
    
    // 分页 页码
    NSInteger currentPage;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *table_top_space;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray<MineRecordsModel *> *dataArray;

@property (strong, nonatomic) AssetHeaderView *headerView;

@end

@implementation MyAssetInfoVC

#pragma mark - Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];

//    self.dataArray =@[@"1", @"2", @"3"].mutableCopy;
    self.dataArray = [NSMutableArray array];
    [self initHeaderView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)initHeaderView {
    CGFloat header_height =160;
    if (self.typeVC ==2) {
        header_height =170;
    } else if (self.typeVC ==3) {
        header_height =130;
    }
    self.headerView =[AssetHeaderView loadNib:@"AssetHeaderView" frame:CGRectMake(0, 0, KScreenWidth, header_height)];
    self.headerView.moneyType =self.typeVC;
    [self.headerView didRechargeButtonBlock:^(UIButton *button) {
        if (self.typeVC ==1) {
            [MyAssetInfoVC rechargeAlertView_rechargeRusult:^(NSInteger type) {
                NSLog(@"===%ld", type);
            }];
        } else if (self.typeVC ==2) {
            NSLog(@"提现");
        }
    }];
    [self.view addSubview:_headerView];
    
    self.table_top_space.constant =header_height+10;
    
    // 设置tableview 分页刷新相关
    currentPage = 1;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 1;
        [self.dataArray removeAllObjects];
        [self _requestNetwork];
        [self.tableView.mj_footer setState:MJRefreshStateIdle];
        
    }];
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self _requestNetwork];
    }];
    
}




#pragma mark - Request Network
- (void)_requestNetwork {
    
    NSString *url = @"";
    
    switch (_typeVC) {
        case 1:
        {
            url = @"userCashRecord/selectAllGoldRecords";
        }
            break;
        case 2:
        {
            url = @"userCashRecord/selectAllCashRecords";
        }
            break;
        case 3:
        {
            url = @"userCashRecord/selectAdProfitMoneyList";
        }
            break;
        default:
            break;
    }
 
    
    
    [HttpUrl NetErrorGET:url dict:@{@"curret":@(currentPage)} hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            NSArray *dataArr = data[@"data"];
            
            NSArray *list = data[@"data"][@"list"];
            
            if (list.count > 0) {
                [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MineRecordsModel *model = [MineRecordsModel mj_objectWithKeyValues:obj];
                    [self.dataArray addObject:model];
                }];
            } else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
        }
    } WithFailBlock:^(id data) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
    [HttpUrl GET:@"userAccount/selectMyAccount" dict:nil hud:self.view isShow:NO WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            
            UserAccountModel *accountModel = [UserAccountModel mj_objectWithKeyValues:data[@"data"]];
            NSString *tempStr = @"0";
            switch (_typeVC) {
                case 1:
                    tempStr = [NSString stringWithFormat:@"%ld", accountModel.allGold];
                    break;
                case 2:
                    tempStr = [NSString stringWithFormat:@"%.2lf", accountModel.balanceMoney];
                    break;
                case 3:
                    tempStr = [NSString stringWithFormat:@"%.2lf", accountModel.adProfitMoney];
                    break;
                default:
                    break;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                self.headerView.moneyLabel.text = tempStr;
            });
        }}];
}


/// 充值弹框(-2:用户取消 -1:调用接口失败 1:调用成功  (其它请自定义))
+ (void)rechargeAlertView_rechargeRusult:(void (^)(NSInteger type))newBlock {
    AlertBgView *alertView =[[AlertBgView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) clickRemove:NO bgColor:[UIColor colorWithWhite:0 alpha:0.6]];
    [alertView showView];
    alertView.centerView_height.constant =465;
    
    RechargeListView *rechargeView =[RechargeListView loadNib:@"RechargeListView" frame:CGRectMake((KScreenWidth-310)/2.0, 0, 310, alertView.centerView_height.constant)];
    [rechargeView buttonClickBlock:^(UIButton *button, id value) {
        if (button ==rechargeView.closeButton) {
            [rechargeView removeFromSuperview];
            [alertView removeView];
            newBlock(-2);
        } else {
            NSDictionary *data =(NSDictionary *)value;
            [MyAssetInfoVC selectPayTypeAlertView:alertView.centerView animationView:rechargeView playMoney:[data[@"money"] floatValue] recharge:^(NSInteger type) {
                newBlock(type);
            }];
        }
    }];
    [alertView.centerView addSubview:rechargeView];
}


/// 选择支付弹框
+ (void)selectPayTypeAlertView:(UIView*)supView animationView:(UIView *)animation playMoney:(CGFloat)money recharge:(void (^)(NSInteger type))newBlock {
    if (animation) {
        [UIView animateWithDuration:0.30 animations:^{
            animation.alpha =0;
        } completion:^(BOOL finished) {
            animation.hidden =YES;
        }];
    }
    CGFloat minY =(CGRectGetHeight(supView.frame)-300)/2.0;
    PayTypeAlertView *payTypeView =[PayTypeAlertView loadNib:@"PayTypeAlertView" frame:CGRectMake((KScreenWidth-310)/2.0, minY, 310, 300)];
    payTypeView.headerView.moneyLabel.text =[NSString stringWithFormat:@"¥%.2f", money];
    [payTypeView didButtonClickBlock:^(UIButton *button) {
        if (button ==payTypeView.headerView.closeButton) {
            if (animation) {    // 隐藏支付选择动画并移除
                [UIView animateWithDuration:0.30 animations:^{
                    payTypeView.alpha =0;
                } completion:^(BOOL finished) {
                    [payTypeView removeFromSuperview];
                }];
                // 显示充值列表
                animation.alpha =1;    animation.hidden =NO;
                [animation startAnimation:UIViewTransitionTypeTopToBottom];
            } else {
                // 删除所有自定义(AlertBgView)弹框
                [payTypeView removeFromSuperview];
                [supView.superview removeFromSuperview];
                newBlock(-2);
            }
        } else {
            NSLog(@"支付方式:%ld====支付金额:%.2f", payTypeView.selectIndex, money);
            // 支付宝支付
            if (payTypeView.selectIndex == 0) {
                APOrderInfo* order = [APOrderInfo new];
                
//                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//                    NSLog(@"reslut = %@",resultDic);
//                }];
                
            } else {  // wx 支付
             
                
                
            }
            
            
            
            
            /* 示例示例
            [RequestManager postRequestURL:@"请求完整地址" parameter:@{@"key":@"value"} withBlock:^(id object, NSError *error) {
                if (object) {
                    if (Request_Success) {
                        NSLog(@"Request=%@", object);
                        newBlock(1);
                    } else {
                        ShowAlertTitle(object[@"msg"]);
                        newBlock(-1);
                    }
                } else {
                    newBlock(-1);
                    ShowAlertTitle(@"服务器或网络错误,请稍后再试");
                }
            }];
             */
        }
    }];
    [supView addSubview:payTypeView];
    [supView startAnimation:UIViewTransitionTypeBottomToTop];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AssetInfoCell *cell =[tableView dequeueReusableCellWithIdentifier:@"AssetInfoCell"];
    if (!cell) {
        cell =[AssetInfoCell findCellWithIdentifier:@"AssetInfoCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    // cell数据
    MineRecordsModel *mineRecordsModel = self.dataArray[indexPath.row];
    cell.titleLabel.text = mineRecordsModel.title;
    cell.subTitleLabel.text = mineRecordsModel.gmtDatetime;
    cell.moneyLabel.text = [NSString stringWithFormat:@"+%@", mineRecordsModel.money];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
